package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderHandlerInterceptorContext implements ApplicationContextAware {

    // 定义一个List存储责任链中具体的任务对象
    public static  List<OrderHandlerInterceptor> orderHandlerInterceptors = new ArrayList<>();


    // 提供责任链入口方法
    public static OrderInfoVo entry(OrderInfoVo orderInfoVo){
        for (OrderHandlerInterceptor orderHandlerInterceptor : orderHandlerInterceptors){
            orderInfoVo = orderHandlerInterceptor.sbumitOrderRequestProcess(orderInfoVo);
        }
         return orderInfoVo;
    }

    // 获取责任链任务对象，将其存储到orderHandlerInterceptors集合中
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderHandlerInterceptor> beansOfType = applicationContext.getBeansOfType(OrderHandlerInterceptor.class);
        beansOfType.values().stream().sorted((o1 , o2) -> o1.sort() - o2.sort()).forEach(orderHandlerInterceptor -> {
            orderHandlerInterceptors.add(orderHandlerInterceptor);
        });
    }
}